<template>
  <el-form
    ref="myform"
    :model="reactiveparams"
    class="demo-form-inline"
    :label-width="props.labelWidth ? props.labelWidth + 'px' : ''"
  >
    <el-row :gutter="20" :justify="!props.isshowtool ? 'center' : 'end'">
      <el-col
        v-for="(item, i) in props.forms"
        :key="i"
        :style="{
          display: isExpand ? (i > indexNum ? 'none' : 'block') : 'block',
          margin: '5px 0px',
          'text-align': 'left',
        }"
        :sm="12"
        :md="12"
        :lg="!props.isshowtool ? 15 : selector ? 8 : 6"
        :xl="6"
      >
        <el-form-item
          :label="item.label"
          :rules="item.rules || []"
          :prop="item.modelValue"
          :label-width="getLabelWidth(item.label) + 'px'"
        >
          <el-input
            :style="item.itemWidth ? `width: ${item.itemWidth}px;` : ''"
            v-if="item.fieldType === 'input' || item.fieldType === undefined"
            v-model="reactiveparams[item.modelValue]"
            :placeholder="`请输入${item.label}`"
            clearable
          />
          <el-input
            :style="item.itemWidth ? `width: ${item.itemWidth}px;` : ''"
            v-else-if="item.fieldType === 'psw'"
            show-password
            v-model="reactiveparams[item.modelValue]"
            :placeholder="`请输入${item.label}`"
            clearable
          />
          <el-select
            v-else-if="item.fieldType === 'select'"
            v-model="reactiveparams[item.modelValue]"
            :disabled="item.disabled"
            :style="item.itemWidth ? `width: ${item.itemWidth}px;` : ''"
            :placeholder="item.placeholder ? item.placeholder : '请选择'"
            clearable
          >
            <el-option
              v-for="(option, optionIndex) in item.options"
              :key="optionIndex + '_local'"
              :value="
                typeof option === 'object'
                  ? option[item.valueKey || 'value']
                  : option
              "
              :label="
                typeof option === 'object'
                  ? option[item.labelKey || 'label']
                  : option
              "
            />
          </el-select>
          <!-- 日期-->
          <el-date-picker
            v-else-if="item.fieldType === 'date'"
            v-model="reactiveparams[item.modelValue]"
            :placeholder="item.placeholder"
            :disabled="item.disabled"
            :readonly="item.readonly"
            :style="item.itemWidth ? `width: ${item.itemWidth}px;` : ''"
            :editable="item.editable"
            :picker-options="item.pickerOptions || {}"
            :type="item.dateType || 'date'"
          />
          <!-- 日期范围-->
          <el-date-picker
            v-else-if="item.fieldType === 'daterange'"
            v-model="reactiveparams[item.modelValue]"
            :disabled="item.disabled"
            :readonly="item.readonly"
            :style="item.itemWidth ? `width: ${item.itemWidth}px;` : ''"
            :editable="item.editable"
            :placeholder="item.placeholder ? item.placeholder : '请选择'"
            :start-placeholder="
              item.startPlaceholder ? item.startPlaceholder : '请选择'
            "
            :end-placeholder="
              item.endPlaceholder ? item.endPlaceholder : '请选择'
            "
            :picker-options="item.pickerOptions || {}"
            type="daterange"
            @change="(date) => changeDate(date, item.prop[0], item.prop[1])"
          />
          <template v-else-if="item.fieldType === 'slot'">
            <slot :name="item.slotName" :item="item" />
          </template>
        </el-form-item>
      </el-col>
      <el-col
        :xs="12"
        :sm="12"
        :md="12"
        :lg="selector ? 8 : 6"
        :xl="10"
        :offset="offset"
        class="ibps-mt-5 ibps-tc"
        v-show="props.isshowtool"
      >
        <div class="tools">
          <el-button
            v-for="(btn, i) in props.toolbars"
            :key="i"
            :type="btn.type ? btn.type : 'primary'"
            @click.prevent.stop="handleAction(btn.key)"
          >
            <span v-if="btn.key == 'search'">搜索</span>
            <span v-else>{{ btn.label }}</span>
          </el-button>
          <div
            @click="handleExpand"
            style="cursor: pointer"
            v-show="displayIcon"
          >
            <el-icon v-if="isExpand"><ArrowDownBold /></el-icon>
            <el-icon v-else><ArrowUpBold /></el-icon>
            {{ isExpand ? "展开" : "收起" }}
          </div>
        </div>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup>
import { reactive, ref, toRaw, computed, onUpdated } from "vue";
const props = defineProps({
  forms: Object,
  toolbars: Array,
  isshowtool: {
    type: Boolean,
    default: true,
  },
  labelWidth: {
    type: Number,
    default: 75,
  },
});
const emit = defineEmits(["handleAction", "getParams",'handleExpand']);
console.log(props);
const params = {};
const datePrefix = "daterange-prefix";
console.log(props.forms);
props.forms.forEach((v, i) => {
  const propType = typeof v.prop;
  if (propType === "string") {
    v.modelValue = v.prop;
    params[v.prop] = v.value || "";
    if (v.format) {
      format[v.prop] = v.format;
    }
  } else if (
    propType === "object" &&
    Object.prototype.toString.call(v.prop) === "[object Array]"
  ) {
    v.prop.forEach((vv, j) => {
      params[vv] = vv.value || "";
      if (v.format) {
        format[vv] = v.format;
      }
    });
  }
  if (v.fieldType === "daterange") {
    params[datePrefix + i] = "";
    v.modelValue = datePrefix + i;
    // params[v.prop[0]]=v.value[0]
    // params[v.prop[1]]=v.value[1]
  } else if (v.fieldType === "select" && (v.selectFetch || v.selectUrl)) {
    const dataKey = selectOptionPrefix + i;
    dataObj.selectOptions[dataKey] = [];
    if (!v.selectMethod) {
      v.selectMethod = "get";
    }
  }
});
console.log(params);
let reactiveparams = reactive(params);
const clientWidth = ref(document.body.clientWidth);
const selector = ref(0);
let isExpand = ref(props.isshowtool ? true : false);
let myform = ref();

const handleAction = (command, position, selection, data) => {
  emit("handleAction", command, position, selection,);
};
const getParams = (callback) => {
  myform.value.validate((valid, fields) => {
    if (valid) {
      const formattedForm = {};
      Object.keys(reactiveparams).forEach((v) => {
        const val = reactiveparams[v];
        let key = v;
        formattedForm[key] = val;
      });
      if (callback) callback(null, formattedForm);
    } else {
      if (callback) callback(new Error());
    }
  });
};
const resetSearchForm = () => {
  try {
    myform.value.resetFields();
  } catch (error) {
    console.error(error);
  }
  Object.keys(reactiveparams).forEach((v) => {
    reactiveparams[v] = "";
  });
};
const indexNum = computed(() => {
  if (clientWidth.value >= 1920) {
    return 2;
  } else if (clientWidth.value >= 1200 && clientWidth.value < 1920) {
    return selector.value ? 1 : 2;
  } else {
    return 0;
  }
});
const offset = computed(() => {
  let lableNum = 0;
  let offsetNum = 0;
  if (clientWidth.value >= 1920) {
    lableNum = 4;
    offsetNum = 6;
  } else if (clientWidth.value >= 1200 && clientWidth.value < 1920) {
    lableNum = selector.value ? 3 : 4;
    offsetNum = selector.value ? 8 : 6;
  } else {
    lableNum = 2;
    offsetNum = 12;
  }
  // 展开
  if (isExpand) {
    return props.forms.length < lableNum
      ? Math.abs(lableNum - 1 - props.forms.length) * offsetNum
      : 0;
  } else {
    // 收缩
    return Math.abs(lableNum - 1 - (props.forms.length % lableNum)) * offsetNum;
  }
});
const changeDate = (date, startDate, endDate) => {
  let dates;
  if (date === null) {
    params[startDate] = "";
    params[endDate] = "";
    return;
  }
  if (typeof date === "string") {
    dates = date.split(" - ");
  } else if (date && date.hasOwnProperty("length")) {
    const firstDate = date[0];
    const secondDate = date[1];
    dates = [
      `${firstDate.getFullYear()}-${("0" + (firstDate.getMonth() + 1)).substr(
        -2
      )}-${("0" + firstDate.getDate()).substr(-2)}`,
      `${secondDate.getFullYear()}-${("0" + (secondDate.getMonth() + 1)).substr(
        -2
      )}-${("0" + secondDate.getDate()).substr(-2)}`,
    ];
  }
  params[startDate] = dates[0];
  params[endDate] = dates[1];
};
const handleExpand = () => {
  isExpand.value = !isExpand.value;
    emit("handleExpand");
};
const displayIcon = computed(() => {
  if (clientWidth.value >= 1920) {
    return !(props.forms.length < 4);
  } else if (clientWidth.value >= 1200 && clientWidth.value < 1920) {
    return !(
      (selector.value && props.forms.length < 3) ||
      (!selector.value && props.forms.length < 4)
    );
  } else {
    return !(props.forms.length < 1);
  }
});
defineExpose({
  getParams,
  resetSearchForm,
  isExpand
});
const getLabelWidth = (label) => {
  let labelLength = getTextFullLength(label);
  const labelSuffixLength = getTextFullLength("：");
  if (labelLength > 10) {
    labelLength = 10;
  }
  return ((labelLength + labelSuffixLength) * 25) / 2;
};
const getTextFullLength = (text = "") =>
  text.split("").reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0);
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1;
    }
    return pre + 2;
  }, 0);
</script>